<template>
  <div class="comment">
    <div class="submitbox">
      <h3>提交评论</h3>
      <div>
        <x-textarea :rows="6" v-model="commentVal"></x-textarea>
        <x-button mini @click.native="submitComment">发表</x-button>
      </div>
      <!-- 提示 -->
      <toast v-model="isShowTips" type="text" :time="800" is-show-mask :text="showText" :position="'top'"></toast>
    </div>
    <div class="commentbox">
      <h3 class="line">评论详情</h3>
      <ul>
        <li v-for="(item,index) in commentsList" :key="index">
          <h4 class="comment-content">{{item.content}}</h4>
          <p><span class="comment-user">{{item.user_name}}</span><span class="comment-time">{{item.add_time}}</span></p>
        </li>
      </ul>
    </div>
    <div class="button-group">
      <x-button @click.native="loadMore" v-if="isMore">加载更多</x-button>
      <x-button plain type="warn" v-else>没有更多</x-button>
    </div>
  </div>
</template>

<script>
import { XButton, XTextarea, Toast } from 'vux'
import { getCommentsList, postSubmitCommet } from '@/api'
export default {
  components: {
    XButton,
    XTextarea,
    Toast
  },
  data () {
    return {
      pageindex: 1,
      commentsList: [],
      isMore: true,
      commentVal: '',
      isShowTips: false,
      showText: ''

    }
  },
  created () {
    this.initList()
  },
  methods: {
    // 初始化评论列表
    initList () {
      getCommentsList(this.$route.params.id || 37, this.pageindex).then(res => {
        console.log(res)
        // this.commentsList = res.message
        // 旧数据
        let oldComments = this.commentsList
        // 将旧数据拼接请求回来的新数据再赋值给数组
        this.commentsList = [...oldComments, ...res.message]
        if (res.message.length < 10) {
          this.isMore = false
        }
      })
    },
    // 提交评论
    submitComment () {
      // 判断内容是否为空
      if (this.commentVal.trim() === '') {
        this.showText = '评论不能为空'
        this.isShowTips = true
      } else {
        // 处理好数据，发送请求
        console.log(this.commentVal)
        postSubmitCommet(this.$route.params.id || 37, 'content=' + this.commentVal).then(res => {
          console.log(res)
          if (res.status === 0) {
            this.showText = '评论提交成功'
            this.isShowTips = true
            // 现将数组清空在发请求，避免重复
            this.commentsList = ''
            this.initList()
            this.commentVal = ''
          }
        })
      }
    },
    // 加载更多
    loadMore () {
      this.pageindex++
      this.initList()
    }
  }
}
</script>

<style lang="less" scoped>
.inputbox {
  border: 1px solid #999;
}
.comment h3 {
  font-weight: bold;
  margin: 10px 0;
  font-size: 14px;
}
.line {
  border-top: 1px solid #999;
  padding-top: 10px;
}
.commentbox{
  li:not(:last-child) {
    border-bottom: 1px solid #999;
    margin: 5px 0;
  }
  p {
    font-size: 14px;
  }
  .comment-content {
    color: #999;
    font-size: 14px;
  }
}
.comment-user, .comment-time {
  font-size: 12px;
  color: #26a2ff;
}
</style>
